// src/pages/Home/RoleManagement/index.js
import React, { useState } from 'react';
import {
  Table, Button, Modal, Form, Input,
  Checkbox, message, Card, Space, Switch,
  Tabs, Tree
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  LockOutlined,
  ApiOutlined,
  MenuOutlined
} from '@ant-design/icons';
import AuthButton from '@/components/Permission/AuthButton';

const { TabPane } = Tabs;

const RoleManagement = () => {
  const [roles, setRoles] = useState([
    {
      id: 1,
      name: '管理员',
      description: '系统管理员，拥有所有权限',
      permissions: [
        'user:list', 'user:create', 'user:edit', 'user:delete',
        'role:list', 'role:create', 'role:edit', 'role:delete'
      ],
      enabled: true
    },
    {
      id: 2,
      name: '普通用户',
      description: '普通用户，只能查看信息',
      permissions: ['user:list'],
      enabled: true
    },
  ]);

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState(null);
  const [form] = Form.useForm();

  // 系统权限结构
  const permissionTreeData = [
    {
      title: '用户管理',
      key: 'user',
      icon: <MenuOutlined />,
      children: [
        { title: '查看用户列表', key: 'user:list', icon: <ApiOutlined /> },
        { title: '创建用户', key: 'user:create', icon: <ApiOutlined /> },
        { title: '编辑用户', key: 'user:edit', icon: <ApiOutlined /> },
        { title: '删除用户', key: 'user:delete', icon: <ApiOutlined /> },
      ]
    },
    {
      title: '角色管理',
      key: 'role',
      icon: <MenuOutlined />,
      children: [
        { title: '查看角色列表', key: 'role:list', icon: <ApiOutlined /> },
        { title: '创建角色', key: 'role:create', icon: <ApiOutlined /> },
        { title: '编辑角色', key: 'role:edit', icon: <ApiOutlined /> },
        { title: '删除角色', key: 'role:delete', icon: <ApiOutlined /> },
      ]
    },
    {
      title: '数据源管理',
      key: 'datasource',
      icon: <MenuOutlined />,
      children: [
        { title: '查看数据源', key: 'datasource:list', icon: <ApiOutlined /> },
        { title: '创建数据源', key: 'datasource:create', icon: <ApiOutlined /> },
        { title: '编辑数据源', key: 'datasource:edit', icon: <ApiOutlined /> },
      ]
    }
  ];

  const handleAdd = () => {
    setEditingRole(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (role) => {
    setEditingRole(role);
    form.setFieldsValue({
      ...role,
      permissions: role.permissions || []
    });
    setIsModalVisible(true);
  };

  const handleDelete = (roleId) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个角色吗？注意：关联的用户将失去该角色权限。',
      onOk: () => {
        setRoles(roles.filter(role => role.id !== roleId));
        message.success('删除成功');
      }
    });
  };

  const handleToggleStatus = (id, checked) => {
    setRoles(roles.map(role =>
      role.id === id ? { ...role, enabled: checked } : role
    ));
  };

  const handleModalOk = () => {
    form.validateFields().then(values => {
      if (editingRole) {
        setRoles(roles.map(role =>
          role.id === editingRole.id ? { ...values, id: editingRole.id } : role
        ));
        message.success('编辑成功');
      } else {
        const newRole = {
          ...values,
          id: roles.length > 0 ? Math.max(...roles.map(r => r.id)) + 1 : 1,
          enabled: true
        };
        setRoles([...roles, newRole]);
        message.success('添加成功');
      }
      setIsModalVisible(false);
    });
  };

  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '权限数量',
      key: 'permissions',
      render: (_, record) => record.permissions ? record.permissions.length : 0,
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      render: (enabled, record) => (
        <Switch
          checked={enabled}
          onChange={(checked) => handleToggleStatus(record.id, checked)}
        />
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <span>
          <AuthButton permission="role:edit">
            <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
          </AuthButton>
          <AuthButton permission="role:delete">
            <Button type="link" danger onClick={() => handleDelete(record.id)}>删除</Button>
          </AuthButton>
        </span>
      ),
    },
  ];

  return (
    <div>
      <Card
        title={
          <Space>
            <LockOutlined />
            角色权限管理
          </Space>
        }
      >
        <Tabs
          defaultActiveKey="roles"
          items={[
            {
              key: 'roles',
              label: '角色管理',
              children: (
                <>
                  <div style={{ marginBottom: 16 }}>
                    <AuthButton permission="role:create">
                      <Button type="primary" onClick={handleAdd}>新增角色</Button>
                    </AuthButton>
                  </div>

                  <Table
                    columns={columns}
                    dataSource={roles}
                    rowKey="id"
                  />
                </>
              )
            },
            {
              key: 'permissions',
              label: '权限结构',
              children: (
                <Card size="small" title="系统权限结构">
                  <Tree
                    className="demo-tree"
                    treeData={permissionTreeData}
                    defaultExpandAll
                    checkable={false}
                    selectable={false}
                    style={{ padding: '16px' }}
                  />
                </Card>
              )
            }
          ]}
        />
      </Card>

      <Modal
        title={editingRole ? "编辑角色" : "新增角色"}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        destroyOnClose
        width={700}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <Input.TextArea />
          </Form.Item>
          <Form.Item
            name="permissions"
            label="权限配置"
          >
            <Tree
              className="permission-tree"
              treeData={permissionTreeData}
              defaultExpandAll
              checkable
              selectable={false}
              style={{ border: '1px solid #d9d9d9', borderRadius: 4, padding: '16px' }}
              onCheck={(checkedKeys) => {
                // 这里可以处理选中的权限
                console.log('选中的权限:', checkedKeys);
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default RoleManagement;
